package com.clayecloud.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.clayecloud.common.annotation.NoAuthorization;
import com.clayecloud.common.utils.JJWTUtil;
import com.clayecloud.common.utils.MessageUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验handler是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //判断是否包含@NoAuthorization注解，如果包含，直接放行
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }
        //从请求头中获取token
        String token = request.getHeader("Authorization");
        if(StrUtil.isNotEmpty(token)){
            if(JJWTUtil.verifyToken(token)){
                return true;
            }
        }
        //token无效，响应状态为401
        response.setStatus(401); //无权限

        return false;
    }
}
